import 'dart:io';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/foundation.dart';
import '../config/config.dart';
import 'http_manager.dart';

class HttpInterceptors {

  static bool httpInfoLog = true;

  ///用于设置请求代理
  ///httpclient HttpClientAdapter
  ///customProxy 自定义代理，可随时修改
  static void dioProxy(HttpClientAdapter httpclient, {String? customProxy}) {
    //设置代理
    if (customProxy != null) {
      _setDioProxy(httpclient, customProxy);
    } else {
      if (kReleaseMode == false && Config.httpProxy != null) {
        _setDioProxy(httpclient, Config.httpProxy ?? "DIRECT");
      }
    }
  }

  static void _setDioProxy(HttpClientAdapter httpclient, String proxy) {
    (httpclient as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
      // client.badCertificateCallback = (X509Certificate cert, String host, int port) {
      //   return Platform.isAndroid;
      // };
      client.findProxy = (uri) => proxy;
      //抓图片
      var httpClient = ExtendedNetworkImageProvider.httpClient;
      if (httpClient is HttpClient) {
        httpClient.findProxy = (uri) => proxy;
      }
      return client;
    };
  }

  ///设置拦截打印
  static void setupLog(Dio dio) {
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (
        RequestOptions options,
        RequestInterceptorHandler handler,
      ) async {
        // dio.interceptors.requestLock.lock();
        // Response response = await tokenDio.get("/token");
        // options.headers["token"] = response.data["data"]["token"];
        // dio.interceptors.requestLock.unlock();
        return handler.next(options);
      },
      onResponse: (
        Response response,
        ResponseInterceptorHandler handler,
      ) async {
        try {
          if (httpInfoLog == true) {
            var responseStr = response.toString();
            debugPrint("\n=========================我是分割线 开始==========================\n请求baseUrl：${response.requestOptions.baseUrl}\n请求url：${response.requestOptions.path}\n请求头: ${response.requestOptions.headers.toString()}\n请求参数 - FormData: ${response.requestOptions.data?.toString()}\n请求参数 - queryParameters: ${response.requestOptions.queryParameters.toString()}\n请求结果 - headers: ${response.headers}\n请求结果 - body:  $responseStr\n=========================我是分割线 结束==========================\n");
            if (response.data is Map) {
              //请求结果判断
              if (response.data.containsKey("code") == true) {
                int? code = response.data["code"];
                if (code == Http.requestSuccessCode) {
                  //请求成功
                } else {
                  //请求失败
                  // String? message = response.data["msg"];
                }
              }
            }
          }
        } catch (e) {
          debugPrint('onResponse解析错误：$e');
        }
        return handler.next(response);
      },
      onError: (
        DioError err,
        ErrorInterceptorHandler handler,
      ) async {
        try {
          if (httpInfoLog == true) {
            debugPrint("\n=========================我是分割线 开始==========================\n请求baseUrl：${err.requestOptions.baseUrl}\n请求url：${err.requestOptions.path}\n请求头: ${err.requestOptions.headers.toString()}\n请求参数 - FormData: ${err.requestOptions.data?.toString()}\n请求参数 - queryParameters: ${err.requestOptions.queryParameters.toString()}\n请求异常: ${err.toString()}\n=========================我是分割线 结束==========================\n");
            // if (err.response != null) {
            //   debugPrint(' 异常response : ${err.response}');
            //   if (err.response.statusCode == 302) {
            //     debugPrint(' 网络异常信息 302: $err');
            //   } else {
            //     Toast.show('网络异常，请稍候再试');
            //   }
            // } else {
            //   Toast.show('网络异常，请稍候再试');
            // }
          }
        } catch (e) {
          debugPrint('onError解析错误：$e');
        }
        return handler.next(err);
      },
    ));
  }
}
